package br.unifor.mia.sd.proxy;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.net.SocketFactory;

public class HttpDispatcher implements Dispatcher {

	Logger logger = Logger.getLogger("br.unifor.mia.sd.proxy");

	/**
	 * @throws IOException
	 * @throws UnknownHostException
	 * @see br.unifor.mia.sd.proxy.Dispatcher#dispatch(br.unifor.mia.sd.proxy.HttpMessage)
	 */
	public HttpMessage dispatch(HttpMessage message)
			throws UnknownHostException, IOException {

		if (logger.isLoggable(Level.FINEST)) {
			logger.log(Level.FINEST, "Dispatching message for:\n" + "URL - "
					+ message.getUrl() + "\nHost - " + message.getHost()
					+ "\nPort - " + message.getPort() + "\nHTTP Method - "
					+ message.getMethod());
		}


		Socket mySocket = SocketFactory.getDefault().createSocket(
				message.getHost(), message.getPort());
		mySocket.setSoTimeout(10000);
		HttpConnection conn = new HttpConnection(mySocket);
		conn.send(message.getMessage());
		
		// Receiving response
		byte[] msg = conn.receive();
		HttpMessage response = null;

		try {
			response = new HttpMessage(msg);
		} catch (InvalidCreationException ice) {
			logger.log(Level.SEVERE,
					"Could not parse Response Message. Stack: ", ice);
		}

		if (logger.isLoggable(Level.FINEST)) {
			logger.log(Level.FINEST, "Response received: "
					+ new String(response.getMessage()));
		}

		// Freeing resources
		mySocket.close();
		return response;
	}

}
